package com.woniuxy.vuetest.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linke
 * @version 1.0
 * @className: CrossOriginFilter
 * @description: 跨域过滤器
 * @date 2021/11/18 23:06
 * 跨域解决方式三： 配置全局过滤器
 */
@Component
public class CrossOriginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        //运行携带凭证 cookie token
        res.addHeader("Access-Control-Allow-Credentials", "true");
        //所有域
        res.addHeader("Access-Control-Allow-Origin", "*");
        //允许请求方式
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        //允许跨域请求包含content-type
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
}
